package com.markhsiu.core.constant;

import java.lang.reflect.Method;
import java.nio.MappedByteBuffer;
import java.security.AccessController;
import java.security.PrivilegedAction;  

public class ByteUtils {

	/**
	 * 转换数据类型
	 */
	public static final byte TYPE_NULL = 00;//null
	public static final byte TYPE_INT = 31;//1
	public static final byte TYPE_LONG = 32;//2
	public static final byte TYPE_DOUBLE = 33;//3
	public static final byte TYPE_STRING = 34;//4
	
	public static byte[] BT_NULL = new byte[0];

	public static byte[] newByte(int capacity) {
		return new byte[capacity];
	}
	
	public static boolean compare(byte[] a, byte[] b) {
		if (a == null) {
			if (b == null) {
				return true;
			}
			return false;
		}

		if (b == null) {
			return false;
		}

		int aLength = a.length;
		if (aLength != b.length) {
			return false;
		}

		for (int i = 0; i < aLength; i++) {
			if (a[i] != b[i]) {
				return false;
			}
		}

		return true;
	}
 

 
	@SuppressWarnings({ "unchecked", "rawtypes" ,"restriction"})
	public static void cleanMappedByte(MappedByteBuffer buffer) {
		AccessController.doPrivileged(new PrivilegedAction() {
			public Object run() {
				try {
					Method getCleanerMethod = buffer.getClass().getMethod("cleaner", new Class[0]);
					getCleanerMethod.setAccessible(true);
					sun.misc.Cleaner cleaner = (sun.misc.Cleaner) getCleanerMethod.invoke(buffer, new Object[0]);
					cleaner.clean();
				} catch (Exception e) {
					e.printStackTrace();
				}
				return null;
			}
		});
	}
	
	public static void umap(MappedByteBuffer buffer){
		
		try {
			Method cleaner = buffer.getClass().getMethod("cleaner");
			cleaner.setAccessible(true);
			Method clean = Class.forName("sun.misc.Cleaner").getMethod("clean");
			clean.setAccessible(true);
			clean.invoke(cleaner.invoke(buffer));
		} catch (Exception ex) {
		}
		buffer = null;
	}
}
